package com.ycp.erp.login.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.InputFilter;
import android.text.InputType;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.jakewharton.rxbinding2.view.RxView;
import com.one.common.config.CMemoryData;
import com.one.common.config.MyContact;
import com.one.common.config.RouterPath;
import com.one.common.manager.RouterManager;
import com.one.common.model.extra.DefaultExtra;
import com.one.common.utils.ClickUtils;
import com.one.common.utils.EditTextGangedUtils;
import com.one.common.utils.ResourceUtils;
import com.one.common.utils.SPUtils;
import com.one.common.utils.ScreenUtils;
import com.one.common.view.base.BaseActivity;
import com.one.common.view.dialog.BottomListDialog;
import com.one.common.view.dialog.item.DialogListItem;
import com.one.common.view.widget.ClearEditView;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.ycp.erp.R;
import com.ycp.erp.login.mobel.param.SendCodeParam;
import com.ycp.erp.login.presenter.LoginPresenter;
import com.ycp.erp.login.view.SendCodeView;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;


/**
 * Author: zhulunjun
 * Email: zhulunjun@qq.com
 * CreateDate: 2018/11/15 10:44
 * Description：登录界面
 **/
@Route(path = RouterPath.LOGIN_PAGE)
public class LoginActivity extends BaseActivity<LoginPresenter> implements SendCodeView, ScreenUtils.KeyboardListener {

    private static final int TYPE_PWD = 1;
    private static final int TYPE_VERIFY = 2;
    @BindView(R.id.et_phone)
    ClearEditView etPhone;
    @BindView(R.id.et_pwd)
    ClearEditView etPwd;
    @BindView(R.id.iv_show_pwd)
    ImageView ivShowPwd;
    @BindView(R.id.tv_btn_verify)
    TextView tvBtnVerify;
    @BindView(R.id.tv_btn_login)
    TextView tvBtnLogin;
    @BindView(R.id.tv_register)
    TextView tvRegister;
    @BindView(R.id.tv_check_verify)
    TextView tvCheckVerify;
    @BindView(R.id.tv_forget_pwd)
    TextView tvForgetPwd;
    @BindView(R.id.iv_logo)
    ImageView ivLogo;
    @BindView(R.id.ll_show_pwd)
    LinearLayout llShowPwd;

    /**
     * 登录类型
     */
    private int type = TYPE_PWD;
    /**
     * 忘记密码弹窗
     */
    private BottomListDialog bottomListDialog;

    @Override
    protected void initPresenter() {
        mPresenter = new LoginPresenter(this, this);
    }

    @Override
    public int getLayoutResId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initTitle() {
        super.initTitle();
        noHasTitle();
    }

    @Override
    public void initView() {
        super.initView();
        ARouter.getInstance().inject(this);
        etPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        EditTextGangedUtils.setEtLengthWithSendEnable(this, etPhone, tvBtnVerify);
        EditTextGangedUtils.setEWithImage(this, etPwd, ivShowPwd);
        EditTextGangedUtils.setEnableWithDoubleEt(this, etPhone, etPwd, tvBtnLogin);
        ScreenUtils.setOnkeyboardListener(this, this);
//
//        if (CMemoryData.isDriver()) {
//            tvRegister.setVisibility(View.INVISIBLE);
//        }
//        if(CMemoryData.isCar()){
//           sendBroadcast(ServiceUtils.getCloseBrodecastIntent());
//           stopService(new Intent(this, LocationService.class));
//            new NotificationHandle(this)
//                    .getManager().cancel(NOTI_ID);
//        }

        if(SPUtils.getBoolean("show_protocol",true)){
            RouterManager.getInstance().go(RouterPath.PROTOCOL_SHOW);
            SPUtils.putBoolean("show_protocol",false);
        }

        register();
    }

    /**
     * 登录
     */
    @OnClick(R.id.tv_btn_login)
    public void login(View view) {
        if (type == TYPE_PWD) {
            mPresenter.loginPwd(etPhone.getText().toString(), etPwd.getText().toString());
        } else {
            mPresenter.loginVerify(etPhone.getText().toString(), etPwd.getText().toString());
        }
    }

    /**
     * 注册
     */
    @SuppressLint("CheckResult")
    public void register() {
            //角色选择
            RxView.clicks(tvRegister).throttleFirst(2, TimeUnit.SECONDS).subscribe((object)->{

                        if (CMemoryData.isCar()){
                            RouterManager.getInstance().go(RouterPath.CARROLESELECT);
                        }else {
                            RouterManager.getInstance().go(RouterPath.REGISTER,
                                    new DefaultExtra(etPhone.getText().toString()));
                        }
            });
        }

    /**
     * 切换登录方式
     */
    @OnClick(R.id.tv_check_verify)
    public void checkLogin() {
        if (type == TYPE_PWD) {
            toVerifyLogin();
        } else {
            etPwd.setText("");
            type = TYPE_PWD;
            llShowPwd.setVisibility(View.VISIBLE);
            ivShowPwd.setVisibility(View.VISIBLE);
            tvForgetPwd.setVisibility(View.VISIBLE);
            tvBtnVerify.setVisibility(View.GONE);
            etPwd.setHint("请输入密码");
            tvCheckVerify.setText(com.one.common.R.string.login_verify_type);
            etPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            etPwd.setFilters(new InputFilter[]{new InputFilter.LengthFilter(16)});
        }
    }

    /**
     * 切换验证码登录
     */
    private void toVerifyLogin() {
        type = TYPE_VERIFY;
        etPwd.setText("");
        llShowPwd.setVisibility(View.GONE);
        ivShowPwd.setVisibility(View.GONE);
        tvForgetPwd.setVisibility(View.GONE);
        tvBtnVerify.setVisibility(View.VISIBLE);
        etPwd.setHint("请输入验证码");
        etPwd.setInputType(InputType.TYPE_CLASS_NUMBER);
        tvCheckVerify.setText(getString(com.one.common.R.string.login_pwd_type));
        etPwd.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});


//        findViewById(R.id.tv_btn_verify).setOnClickListener(v -> {
//            sendCode(v);
//        });
//
//        findViewById(R.id.tv_btn_login).setOnClickListener(v ->{
//                login(v);});
    }

    /**
     * 忘记密码
     */
    @OnClick(R.id.tv_forget_pwd)
    public void forgetPwd() {
        if (ClickUtils.isFastClick()) return;
        showListDialog();
    }

    /**
     * 切换密码显示
     */
    @OnClick(R.id.iv_show_pwd)
    public void showPwd() {
        EditTextGangedUtils.setEtInputTypeWithImge(etPwd, ivShowPwd);
    }

    /**
     * 发送验证码
     */
    @OnClick(R.id.tv_btn_verify)
    public void sendCode(View view) {
//        startCountDown();
        if (ClickUtils.isFastClick()) return;
        mPresenter.sendCode(etPhone.getText().toString(), SendCodeParam.TYPE_LOGIN);
    }

    /**
     * 开始倒计时
     */
    private Disposable disposableVerify;

    @SuppressLint("CheckResult")
    public void startCountDown() {
        if (type != TYPE_VERIFY) {
            toVerifyLogin();
        }
        Observable.interval(0, 1, TimeUnit.SECONDS)
                .take(COUNT_DOWN_SECOND + 1)
                .doOnSubscribe(disposable -> {
                    disposableVerify = disposable;
                    tvBtnVerify.setEnabled(false);
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(AndroidSchedulers.mainThread())
                .compose(this.<Long>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(
                        aLong ->
                                tvBtnVerify.setText(COUNT_DOWN_SECOND - aLong + "s重发"),
                        throwable ->
                                throwable.printStackTrace(),
                        () -> {
                            resetCountDown();   // 重置倒计时
                        });
    }

    /**
     * 重置倒计时
     */
    public void resetCountDown() {
        try {
            disposableVerify.dispose();
            tvBtnVerify.setEnabled(true);
            tvBtnVerify.setText(ResourceUtils.getString(com.one.common.R.string.get_verify));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 忘记密码弹窗
     */
    private void showListDialog() {
        ArrayList<DialogListItem> items = new ArrayList<>();
        if (CMemoryData.getAppSorce().equals(MyContact.CAR)){
            items.add(new DialogListItem("修改手机号",0));
        }
        items.add(new DialogListItem("通过短信验证码登录", 1));
        items.add(new DialogListItem("找回密码", 2));
        bottomListDialog = new BottomListDialog(this, items);
        bottomListDialog.setItemClickListener((item, position) -> {

            switch (item.getType()){
                case 0:
                    RouterManager.getInstance().go(RouterPath.MODIFY_PHONE_NUMS);
                    break;
                case 1:
                    if (type != TYPE_VERIFY) {
                        toVerifyLogin();
                    }
                    break;
                case 2:
                    RouterManager.getInstance().go(RouterPath.FORGET_PWD,
                            new DefaultExtra(etPhone.getText().toString()));
                    break;
            }
        });
        bottomListDialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bottomListDialog != null && bottomListDialog.isShowing()) {
            bottomListDialog.dismiss();
            bottomListDialog = null;

        }
    }


    @Override
    public void onShow(boolean isShow, int changeSize) {
        if (ivLogo != null) {
            if (isShow) {
                ivLogo.setVisibility(View.GONE);
            } else {
                ivLogo.setVisibility(View.VISIBLE);
            }
        }
    }
}
